package com.util;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.bean.users.usersBean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

public class usersUtil {
    private static Connection source = null;
    public static Connection utils(){
        if(source==null){
            try {
                Class.forName("com.mysql.jdbc.Driver");
                String url = "jdbc:mysql://localhost:3306/huagong?characterEncoding=UTF-8";
                String user = "root";
                String password = "123456";
                source = DriverManager.getConnection(url,user,password);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return source;
    }
    /**
     * 查询全部业务员
     */
    public static List<usersBean> selectAll() throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "select * from users";
        List<usersBean> list = qr.query(usersUtil.utils(),sql,new BeanListHandler<usersBean>(usersBean.class));
        return list;
    }
    /**
     * 修改业务员信息
     */
    public static void update(Object...objects) throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "UPDATE users set user_name=?,password=?,type=? where uid=?";
        qr.update(usersUtil.utils(),sql,objects);
    }
    /**
     * 删除业务员
     */
    public static void delete(String uid) throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "DELETE from users where uid=?";
        qr.update(purchaseUtil.utils(),sql,uid);
    }
    /**
     * 查询业务员身份
     */
    public static usersBean selectUserType(String uid) throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql= "select type from users where uid=?";
        usersBean users = qr.query(usersUtil.utils(),sql,new BeanHandler<usersBean>(usersBean.class),uid);
        return users;
    }

    /**
     * 添加业务员
     * @param objects
     * @throws SQLException
     */
    public static void insert(Object...objects) throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "insert into users(user_name,password,type) VALUES(?,?,?)";
        qr.update(usersUtil.utils(),sql,objects);
    }
}
